package com.ruoyi.finance.test;

import redis.clients.jedis.Jedis;
import java.util.Random;

public class CacheAvalancheSolution {
    private static final int CACHE_SIZE = 100;
    private static final int MIN_EXPIRE_TIME = 60;
    private static final int MAX_EXPIRE_TIME = 120;
    private static Jedis jedis = new Jedis("localhost", 6379);
    private static Random random = new Random();

    public static void main(String[] args) {
        // 模拟缓存批量设置，过期时间随机化
        for (int i = 0; i < CACHE_SIZE; i++) {
            String key = "key_" + i;
            String value = "value_" + i;
            int expireTime = MIN_EXPIRE_TIME + random.nextInt(MAX_EXPIRE_TIME - MIN_EXPIRE_TIME + 1);
            jedis.setex(key, expireTime, value);
        }

        // 模拟一段时间后部分缓存失效，请求访问缓存
        for (int i = 0; i < CACHE_SIZE; i++) {
            String key = "key_" + i;
            String value = jedis.get(key);
            if (value == null) {
                // 缓存失效，从数据库获取数据
                value = getDataFromDatabase(key);
                // 重新设置缓存，过期时间随机化
                int expireTime = MIN_EXPIRE_TIME + random.nextInt(MAX_EXPIRE_TIME - MIN_EXPIRE_TIME + 1);
                jedis.setex(key, expireTime, value);
            }
            System.out.println("Key: " + key + ", Value: " + value);
        }
        jedis.close();
    }

    private static String getDataFromDatabase(String key) {
        // 模拟从数据库获取数据
        return "db_" + key;
    }
}